package com.hyg.lib_music.ui.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.Music.MusicPreSleepBehavior;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicPreSleepBehaviorViewBinder;
import com.hyg.lib_music.ui.fragment.PostItemDecoration;
import com.hyg.lib_music.util.Ble.BLEUtils;
import com.hyg.lib_music.util.Ble.callback.ConnectCallback;
import com.hyg.lib_music.util.Ble.callback.ScanCallback;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;


import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;
import static me.drakeet.multitype.MultiTypeAsserts.assertHasTheSameAdapter;

public class MusicSleepAcitvity extends BaseActivity implements View.OnClickListener{

    private static final int SPAN_COUNT = 5;
    private ImageView back;
    private TextView bleName;
    Button bt_start_sleep;
    private View bluetooth_not_connected,bluetooth_connected;

    public PopupWindow moreWindow;

    private MultiTypeAdapter mAdapter;
    private ArrayList datas;
    private Items items;
    static String[] NAMES = {"过饱","饮酒","喝茶","喝咖啡","吸烟","焦虑","抑郁","压力大","剧烈运动" };
    static int[] ICOS = {R.mipmap.ic_music_sleep_guobao,R.mipmap.ic_music_sleep_yinjiu,R.mipmap.ic_music_sleep_hecha,R.mipmap.ic_music_sleep_hekafei,R.mipmap.ic_music_sleep_xiyan,R.mipmap.ic_music_sleep_jiaolv,R.mipmap.ic_music_sleep_yiyu,R.mipmap.ic_music_sleep_yalida,R.mipmap.ic_music_sleep_yundong };
    static int[] SELECTED_ICOS = {R.mipmap.ic_music_sleep_guobao_on,R.mipmap.ic_music_sleep_yinjiu_on,R.mipmap.ic_music_sleep_hecha_on,R.mipmap.ic_music_sleep_hekafei_on,R.mipmap.ic_music_sleep_xiyan_on,R.mipmap.ic_music_sleep_jiaolv_on,R.mipmap.ic_music_sleep_yiyu_on,R.mipmap.ic_music_sleep_yalida_on,R.mipmap.ic_music_sleep_yundong_on };

    private static final String BLENAME = "Sleepace_test";
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;
    private ProgressDialog progressDialog;
    private BLEUtils mBleUtils;//蓝牙工具类
    private String mDeviceAddress;//当前连接的mac地址
    private BluetoothDevice mBleDevice;
    public List<BluetoothDevice> mBleDevices;//所有蓝牙设备

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_sleep);
        //设置紫色状态栏
//        this.setStatusBarColor(R.color.musicPrimary);
//        this.setDark(false);
//        this.setStatusBar();
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.musicPrimary),60,null,null,false);

        init();

        //获得实例
        mBleUtils = BLEUtils.getInstance().initble(this);
        if (mBleUtils.isEnable() == true) {
            String deviceAddress = mBleUtils.getBLEDevice(this);
            if (!deviceAddress.equals("")){
                Connect(deviceAddress);//如果蓝牙打开，有上次连接数据，直接连接
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkGps();
    }

    private void init() {
        //返回按钮
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(this);
        View bluetooth_introduction = findViewById(R.id.bluetooth_introduction);
        bt_start_sleep = (Button)findViewById(R.id.bt_start_sleep);
        bleName = (TextView)findViewById(R.id.ble_name);
        bluetooth_not_connected = findViewById(R.id.bluetooth_not_connected);
        bluetooth_not_connected.setOnClickListener(this);
        bluetooth_connected = findViewById(R.id.bluetooth_connected);


        bluetooth_introduction.setOnClickListener(this);
        bt_start_sleep.setOnClickListener(this);
        bt_start_sleep.setEnabled(false);

        RecyclerView mRecyclerView = this.findViewById(R.id.recycler_view);
        mRecyclerView.setBackgroundColor(Color.WHITE);

        final GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT);

        GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return 1;
            }
        };
        layoutManager.setSpanSizeLookup(spanSizeLookup);
        mRecyclerView.setLayoutManager(layoutManager);
        int space = getResources().getDimensionPixelSize(R.dimen.font12);
        mRecyclerView.addItemDecoration(new PostItemDecoration(0, spanSizeLookup));

//        mRecyclerView.setLayoutManager(new GridLayoutManager(this,SPAN_COUNT));

        MusicPreSleepBehaviorViewBinder viewBinder = new MusicPreSleepBehaviorViewBinder();
        viewBinder.setOnMusicPreSleepBehaviorClickListener(new MusicPreSleepBehaviorViewBinder.OnMusicPreSleepBehaviorClickListener() {
            @Override
            public void onItemClick(View view, MusicPreSleepBehavior musicPreSleepBehavior) {
                if (musicPreSleepBehavior.isSelected == true){
                    musicPreSleepBehavior.isSelected = false;
                }else {
                    //清空上次选择
                    for (int i = 0; i < datas.size(); i++) {
                        MusicPreSleepBehavior item = (MusicPreSleepBehavior)datas.get(i);
                        item.isSelected = false;
                    }
                    musicPreSleepBehavior.isSelected = true;
                }
                refresh();
            }
        });
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(MusicPreSleepBehavior.class, viewBinder);

        mRecyclerView.setAdapter(mAdapter);
        assertHasTheSameAdapter(mRecyclerView, mAdapter);

        this.refresh();
    }

    private void refresh() {

        items = new Items();
        if (datas == null){
            datas = new ArrayList();
            for (int i = 0; i < this.NAMES.length; i++) {
                MusicPreSleepBehavior item = new MusicPreSleepBehavior();
                item.name = this.NAMES[i];
                item.ico = this.ICOS[i];
                item.selectedIco = this.SELECTED_ICOS[i];
                datas.add(item);
            }
        }
        for (int i = 0; i < datas.size(); i++) {
            items.add(datas.get(i));
        }
        mAdapter.setItems(items);
        mAdapter.notifyDataSetChanged();
        assertAllRegistered(mAdapter, items);
    }

    public void showMoreWindow(Context context) {

        if (moreWindow == null) {
            moreWindow = new PopupWindow(this);
            moreWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            moreWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            View moreWindowContentView = View.inflate(context, R.layout.dialog_music_bluetooth_noties, null);
            View close = moreWindowContentView.findViewById(R.id.close);
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showMoreWindow(MusicSleepAcitvity.this);
                }
            });
            moreWindow.setContentView(moreWindowContentView);
            moreWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
            moreWindow.setOutsideTouchable(true);
            moreWindow.setFocusable(true);
            moreWindow.setAnimationStyle(R.style.popwindow_anim_style);
            moreWindow.setOnDismissListener(() -> {
                WindowManager.LayoutParams lp1 = ((AppCompatActivity)context).getWindow().getAttributes();
                lp1.alpha = 1f;
                ((AppCompatActivity)context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                ((AppCompatActivity)context).getWindow().setAttributes(lp1);
            });
        }
        if (moreWindow.isShowing()) {
            moreWindow.dismiss();
        } else {
            WindowManager.LayoutParams lp =((AppCompatActivity)context).getWindow().getAttributes();
            lp.alpha = 0.3f; //设置透明度
            ((AppCompatActivity)context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            ((AppCompatActivity)context).getWindow().setAttributes(lp);

            moreWindow.showAtLocation(findViewById(R.id.bg), Gravity.BOTTOM, 0, 0);
        }

    }

    // 控件监听
    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (id == R.id.bluetooth_introduction) {
            showMoreWindow(MusicSleepAcitvity.this);
        } else if (id == R.id.bt_start_sleep) {
            Intent it = new Intent(MusicSleepAcitvity.this, MusicSleepTestActivity.class);

            for (int i = 0; i < datas.size(); i++) {
                MusicPreSleepBehavior item = (MusicPreSleepBehavior) datas.get(i);
                if (item.isSelected) {
                    it.putExtra("PreSleepBehavior", item.name);
                    break;
                }
            }
            MusicSleepAcitvity.this.startActivity(it);
        } else if (id == R.id.back) {// TODO 断开连接
            mBleUtils.CloseBleConn();
            finish();
            overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        } else if (id == R.id.bluetooth_not_connected) {
            scanDevices(true);
        }
    }


    /**
     * 扫描
     *
     * @param enable
     */
    private void scanDevices(final boolean enable) {
        if (mBleUtils.isEnable() == false) {
            Toast.makeText(MusicSleepAcitvity.this,"请先打开蓝牙", Toast.LENGTH_SHORT).show();
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 0);
            return;
        }
        showProgressDialog("请稍候!", "正在扫描...");
        mBleDevices = new ArrayList<BluetoothDevice>();
        mBleUtils.ScanBle(enable, new ScanCallback() {
            @Override
            public void onSuccess() {
                hideProgressDialog();
//                for (BluetoothDevice device:mBleDevices){
//                    if (device.getName()!=null&&device.getName().equals(BLENAME)){//扫描到设备
//                        mBleDevice = device;
//                        String deviceAddress = device.getAddress();
//                        Connect(deviceAddress);
//                        break;
//                    }
//                }
            }

            @Override
            public void onScanning(BluetoothDevice device, int rssi, byte[] scanRecord) {

                if (!mBleDevices.contains(device)) {
                    if (device.getName()!=null&&device.getName().equals(BLENAME)){//扫描到设备
                        mBleDevice = device;
                        String deviceAddress = device.getAddress();
                        Connect(deviceAddress);
                    }
                    mBleDevices.add(device);
                }
            }
        });
    }

    //连接
    private void Connect(String deviceAddress) {
        if (deviceAddress == null) {
            return;
        }
        showProgressDialog("请稍候!", "正在连接...");

        mBleUtils.Connect(deviceAddress, new ConnectCallback() {
            @Override
            public void onConnSuccess() {
                mDeviceAddress = deviceAddress;
                mBleUtils.setBLEDevice(MusicSleepAcitvity.this,mDeviceAddress);
                hideProgressDialog();
                bleName.setText(BLENAME);
                bluetooth_connected.setVisibility(View.VISIBLE);
                bluetooth_not_connected.setVisibility(View.GONE);
                bt_start_sleep.setEnabled(true);
            }

            @Override
            public void onConnFailed() {
                mDeviceAddress = null;
                mBleUtils.setBLEDevice(MusicSleepAcitvity.this,"");
                hideProgressDialog();
                Toast.makeText(MusicSleepAcitvity.this, "连接超时，请重试", Toast.LENGTH_SHORT).show();
                bluetooth_connected.setVisibility(View.GONE);
                bluetooth_not_connected.setVisibility(View.VISIBLE);
            }
        });
    }

    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }
        progressDialog.show();
    }

    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * 开启位置权限
     */
    private void checkGps() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_CODE_ACCESS_COARSE_LOCATION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_ACCESS_COARSE_LOCATION) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                scanDevices(true);
                Toast.makeText(this, "位置权限已开启", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "未开启位置权限", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideProgressDialog();
    }
}
